<template>
  <div style="position: absolute; height: 100%; width: 100%; display: flex; align-items: center; justify-content: center;">
    <div class="video-container" v-show="isPlay" :id="playerId" :style="{ width: width + 'px', height: height + 'px' }"></div>
    <div v-show="!isPlay" style="color: #08979C; font-size: 25px;">暂无视频源</div>
  </div>
</template>

<script>
import { v4 } from 'uuid'

export default {
  name: 'H265Player',
  data() {
    return {
      isPlay: false,
      player: null,
      playerId: '',
      width: 800,
      height: 600
    }
  },
  created() {
    this.playerId = 'h265-player-' + v4() // 避免ID重复
  },
  mounted() {
    // 动态加载H265播放器脚本
    this.loadH265Script()
  },
  methods: {
    // 动态加载H265播放器脚本
    loadH265Script() {
      if (window.new265webjs) {
        return Promise.resolve()
      }

      return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = '/h265web/h265webjs-v20221106.js'
        script.onload = () => {
          console.log('H265播放器脚本加载成功')
          resolve()
        }
        script.onerror = (error) => {
          console.error('H265播放器脚本加载失败:', error)
          reject(error)
        }
        document.head.appendChild(script)
      })
    },

    // 创建播放器
    async createPlayer(url, autoplay = true, index = 0) {
      if (!url) {
        console.warn('H265Player: 播放地址为空')
        return
      }

      try {
        // 确保脚本已加载
        await this.loadH265Script()

        if (this.player) {
          this.changeVideo(url)
          return
        }

        console.log('H265Player: 创建播放器，URL:', url)

        // 获取容器尺寸
        const container = document.getElementById(this.playerId)
        if (container) {
          const rect = container.getBoundingClientRect()
          this.width = rect.width || 800
          this.height = rect.height || 600
        }

        this.isPlay = true

        // 配置H265播放器
        const config = {
          player: this.playerId,
          width: this.width,
          height: this.height,
          token: this.playerId, // 使用播放器ID作为token
          type: this.getVideoType(url),
          extInfo: {
            ignoreAudio: 0, // 启用音频
            autoCrop: true, // 自动裁剪
            core: 1, // 使用核心解码器
            rawFps: 25 // 默认帧率
          }
        }

        console.log('H265Player: 播放器配置:', config)

        // 创建播放器实例
        this.player = window.new265webjs(url, config)

        // 设置播放器事件
        this.setupPlayerEvents()

        console.log('H265Player: 播放器创建成功')

      } catch (error) {
        console.error('H265Player: 创建播放器失败:', error)
        this.isPlay = false
        throw error
      }
    },

    // 设置播放器事件
    setupPlayerEvents() {
      if (!this.player) return

      // 播放完成事件
      this.player.onLoadFinish = () => {
        console.log('H265Player: 视频加载完成')
      }

      // 播放时间事件
      this.player.onPlayTime = (videoPTS) => {
        // console.log('H265Player: 播放时间:', videoPTS)
      }

      // 播放结束事件
      this.player.onPlayFinish = () => {
        console.log('H265Player: 播放结束')
      }

      // 渲染事件
      this.player.onRender = (width, height, imageBufferY, imageBufferB, imageBufferR) => {
        // console.log('H265Player: 渲染帧:', width, height)
      }

      // 缓存进度事件
      this.player.onCacheProcess = (cPts) => {
        // console.log('H265Player: 缓存进度:', cPts)
      }

      // 准备显示完成事件
      this.player.onReadyShowDone = () => {
        console.log('H265Player: 准备显示完成')
      }
    },

    // 获取视频类型
    getVideoType(url) {
      if (url.includes('.flv')) return 'flv'
      if (url.includes('.mp4')) return 'mp4'
      if (url.includes('.m3u8')) return 'hls'
      if (url.includes('.ts')) return 'ts'
      
      // 默认返回flv，因为WVP通常提供FLV流
      return 'flv'
    },

    // 切换视频
    changeVideo(url) {
      console.log('H265Player: 切换视频:', url)
      if (this.player) {
        this.closePlayer()
      }
      this.createPlayer(url)
    },

    // 关闭播放器
    closePlayer() {
      console.log('H265Player: 关闭播放器')
      this.isPlay = false
      
      if (this.player) {
        try {
          this.player.release()
        } catch (error) {
          console.warn('H265Player: 释放播放器失败:', error)
        }
        this.player = null
      }
    },

    // 播放
    play() {
      if (this.player) {
        this.player.do()
      }
    },

    // 暂停
    pause() {
      if (this.player) {
        this.player.pause()
      }
    },

    // 是否正在播放
    isPlaying() {
      return this.player ? this.player.isPlaying() : false
    },

    // 设置音量
    setVolume(volume) {
      if (this.player) {
        this.player.setVoice(volume)
      }
    },

    // 全屏
    fullScreen() {
      if (this.player) {
        this.player.fullScreen()
      }
    },

    // 退出全屏
    closeFullScreen() {
      if (this.player) {
        this.player.closeFullScreen()
      }
    },

    // 截图
    snapshot() {
      if (this.player) {
        this.player.snapshot()
      }
    },

    // 获取媒体信息
    getMediaInfo() {
      return this.player ? this.player.mediaInfo() : null
    }
  },

  beforeUnmount() {
    this.closePlayer()
    console.log('H265Player: 组件销毁')
  }
}
</script>

<style scoped>
.video-container {
  position: relative !important;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.video-container canvas {
  width: 100% !important;
  height: 100% !important;
  object-fit: contain;
}
</style>